import { defineStore } from 'pinia'
import streamApi from '@/api/stream'

export const useStreamStore = defineStore('stream', {
  state: () => ({
    streams: [],
    loading: false,
    error: null
  }),

  getters: {
    activeStreams: (state) => state.streams.filter(stream => stream.status === 'active'),
    inactiveStreams: (state) => state.streams.filter(stream => stream.status !== 'active')
  },

  actions: {
    async fetchStreams(params = {}) {
      this.loading = true
      try {
        const response = await streamApi.getStreams(params)
        this.streams = response.items || response
        this.error = null
        return this.streams
      } catch (error) {
        this.error = error.message
        console.error('获取流列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    async createStream(streamData) {
      try {
        const response = await streamApi.createStream(streamData)
        this.streams.push(response)
        return response
      } catch (error) {
        console.error('创建流失败:', error)
        throw error
      }
    },

    async updateStream(id, streamData) {
      try {
        const response = await streamApi.updateStream(id, streamData)
        const index = this.streams.findIndex(s => s.id === id)
        if (index !== -1) {
          this.streams[index] = response
        }
        return response
      } catch (error) {
        console.error('更新流失败:', error)
        throw error
      }
    },

    async deleteStream(id) {
      try {
        await streamApi.deleteStream(id)
        this.streams = this.streams.filter(s => s.id !== id)
      } catch (error) {
        console.error('删除流失败:', error)
        throw error
      }
    },

    async startStream(id) {
      try {
        const response = await streamApi.startStream(id)
        const index = this.streams.findIndex(s => s.id === id)
        if (index !== -1) {
          this.streams[index].status = 'active'
        }
        return response
      } catch (error) {
        console.error('启动流失败:', error)
        throw error
      }
    },

    async stopStream(id) {
      try {
        const response = await streamApi.stopStream(id)
        const index = this.streams.findIndex(s => s.id === id)
        if (index !== -1) {
          this.streams[index].status = 'inactive'
        }
        return response
      } catch (error) {
        console.error('停止流失败:', error)
        throw error
      }
    }
  }
})